#!/bin/sh

# Pseudo user identity that the collector service will use. This
# should be the name of a "system" UID with very few privileges and no
# shell or login. It will only own a few files and directories in the
# install directory so that it can create the Unix domain socket and
# write to the stdout/stderr logs.
#
# We will create it during the install -- if it doesn't already exist
# (from a previous installation).
#
# The username chosen here must match the `User=` and `Group=` keys
# in the `.service` file.

USERNAME=trace2

INSTALL_LOCATION=/usr/local/sample-trace2-otel-collector

mkdir -p "$INSTALL_LOCATION/logs"
LOGFILE="$INSTALL_LOCATION/logs/install.txt"
exec >>$LOGFILE 2>&1

echo ""
echo ""
echo ""
echo "================================================================"
echo "postinst: X_VER_X"
echo "================================================================"
echo ""
date

set -x

grep "^$USERNAME:" /etc/passwd
if [ $? -eq 0 ]
then
    echo "Using existing pseudo user $USERNAME"
else
    echo "Trying to create system pseudo user $USERNAME"

    /usr/sbin/adduser --system --group --no-create-home $USERNAME
    RESULT=$?
    if [ $RESULT -ne 0 ]
    then
	echo "Could not create pseudo user $USERNAME"
	exit $RESULT
    fi
fi

# Let the service process own the install directory so that it can
# create the Unix domain socket in it.  Also recursively give it
# the logs directory so that it can create/extend the
# stdout/stderr logs.

chown    $USERNAME:$USERNAME $INSTALL_LOCATION
chown -R $USERNAME:$USERNAME $INSTALL_LOCATION/logs

echo Attempting to start sample-trace2-otel-collector
$INSTALL_LOCATION/scripts/service_start

